<template>
  <div>
    <a-input-search style="margin-bottom: 8px" placeholder="Search" @change="search" />
    <a-spin :spinning="spinning">
      <a-tree
        @expand="onExpand"
        :expandedKeys="expandedKeys"
        :autoExpandParent="autoExpandParent"
        :treeData="menuTree"
        @select="selectMenuNode"
        ref="menutree"
      >
        <template slot="title" slot-scope="{title}">
          <span v-if="title.indexOf(searchValue) > -1">
            {{ title.substr(0, title.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ title }}</span>
        </template>
      </a-tree>
    </a-spin>
  </div>
</template>
<script>
import { query } from '@/api/admin'
export default {
  name: 'MenuTree',
  data () {
    return {
      expandedKeys: [],
      autoExpandParent: true,
      menuTree: [],
      spinning: false,
      menuId: '',
      currentitem: '', // 点击菜单节点
      searchValue: '',
      dataList: []
    }
  },
  created () {
    // 获取菜单树
    this.getMenuTree()
  },
  props: {
  },
  methods: {
    /**
     * 获取菜单树
     */
    getMenuTree () {
      this.spinning = true
      query('/admin/pmMenu/buildTree', 'GET')
        .then(res => {
          this.menuTree = this.handleVal(res.result.data)
          generateList(this.menuTree)
          this.spinning = false
        })
        // 将树型结构信息转成列表形式，用于组织信息搜索
      const generateList = (data) => {
        for (let i = 0; i < data.length; i++) {
          const node = data[i]
          const key = node.title
          // 用于树型搜索框添加样式（前台处理需使用递归函数遍历所有子节点，耗用资源，请在后台添加该信息）
          node.scopedSlots = { title: 'title' }
          this.dataList.push({ key, title: key })
          if (node.children) {
            generateList(node.children, node.key)
          }
        }
      }
    },
    /**
     * 处理后台返回值 替换名字 id=>key
     */
    handleVal (value) {
      let str = JSON.stringify(value)
      str = str.replace(/id/g, 'key')
      return JSON.parse(str)
    },
    /**
     * 点击菜单树节点触发右侧列表查询
     */
    selectMenuNode (selectedKeys, e) {
      this.currentitem = e.node._props.dataRef
      this.$emit('selectMenuNode', this.currentitem)
    },
    /**
     * 展开/收起节点时触发
     */
    onExpand  (expandedKeys) {
      // 展开指定树节点
      this.expandedKeys = expandedKeys
    },
    /**
     * 搜索
     */
    search (e) {
      const value = e.target.value
      const expandedKeys = this.dataList.map((item) => {
        if (item.key.indexOf(value) > -1) {
          return this.getParentKey(item.key, this.menuTree).key
        }
        return null
      }).filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true
      })
    },
    /**
     * 获取父节点key
     */
    getParentKey (key, tree) {
      let parentKey
      for (let i = 0; i < tree.length; i++) {
        const node = tree[i]
        if (node.title === key) {
          parentKey = node
        } else {
          if (node.children) {
            if (node.children.some(item => item.title === key)) {
              parentKey = node
            } else if (this.getParentKey(key, node.children)) {
              parentKey = this.getParentKey(key, node.children)
            }
          }
        }
      }
      return parentKey
    }
  }
}
</script>
